<?php
	define('FROM_MW',TRUE);
	
	if ( !defined('ROOTPATH') )
		define('ROOTPATH', dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/');

	if($_POST['from_MW'] == TRUE){
		switch($_POST['action']){
			case 'login':
				op_MediaWiki::from_mw_login();
				break;
			
			case 'logout':
				op_MediaWiki::from_mw_logout();
				break;
			
			default:
				exit();
		}
	}
		
	class op_MediaWiki{
		static function from_mw_login(){
			$username = $_POST['username'];
			$password = $_POST['password'];
			
			// WP logic here
			ob_start();
			
			global $wpdb;
			global $current_user;
			
			require(ROOTPATH.'wp-login.php');
			
			if(isset($current_user)){
				wp_clear_auth_cookie();
			}
		
			ob_end_clean();
	
			if ( is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
				$secure_cookie = false;
			else
				$secure_cookie = '';
				
			$wp_user = wp_signon(array(
				'user_login'	=> $username,
				'user_password'	=> $password
			), $secure_cookie);
			
			echo serialize(headers_list());
			return;
		}
		
		static function from_mw_logout(){
			global $wpdb;
			ob_start();
			require_once(ROOTPATH . '/wp-login.php');
			wp_clear_auth_cookie();
			ob_end_clean();
			return;
		}
		
		function getUserByName($user){
			// Get db connection info from mw settings file
			$include_contents = file_get_contents(ROOTPATH.'/wiki/LocalSettings.php');
			preg_match_all('"^\$wgDB[\w\s\=\'\"]*;"m',$include_contents,$matches);
			
			if(count($matches) == 0){
				return 'Database not configured';
			}
			
			foreach($matches[0] as $match)
				eval($match);
			
			if($wgDBtype != 'mysql')
				return 'Database type not supported';
			
			$dbr = mysql_connect($wgDBserver,$wgDBuser,$wgDBpassword);
			mysql_select_db($wgDBname);
			
			$sql = 'SELECT user_id FROM '.$wgDBprefix.'user WHERE user_name ="'.$user.'"';
			
			$result = mysql_query($sql);
			$user = mysql_fetch_row($result);
			mysql_free_result($result);
			
			return $user;
		}
	}

?>